<template>
  <div class="custom-select" v-click-outside="closeDropdown">
    <div class="select-control" @click="toggleDropdown">
      <div class="selected-tags">
        <span 
          v-for="(item, index) in selectedItems" 
          :key="item.value" 
          class="tag"
        >
          {{ item.text }}
          <span class="remove-tag" @click.stop="removeTag(index)">×</span>
        </span>
        <input
          type="text"
          v-model="searchText"
          @input="handleSearch"
          @focus="openDropdown"
          @keydown.delete="handleBackspace"
          placeholder="请选择或搜索..."
          ref="searchInput"
        >
      </div>
      <span class="arrow-icon">{{ isOpen ? '▲' : '▼' }}</span>
    </div>
    
    <div class="dropdown-menu" v-show="isOpen">
      <div 
        v-for="item in filteredOptions" 
        :key="item.value"
        class="dropdown-item"
        :class="{ 'selected': isSelected(item) }"
        @click="toggleSelection(item)"
      >
        {{ item.text }}
      </div>
      <div v-if="filteredOptions.length === 0" class="no-results">
        无匹配结果
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CustomSelect',
  props: {
    options: {
      type: Array,
      required: true,
      default: () => []
    },
    value: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请选择或搜索...'
    },
    multiple: {
      type: Boolean,
      default: true
    },
    maxSelection: {
      type: Number,
      default: 3
    }
  },
  data() {
    return {
      isOpen: false,
      searchText: '',
      selectedItems: [...this.value]
    }
  },
  computed: {
    filteredOptions() {
      if (!this.searchText) {
        return this.options.filter(option => 
          !this.selectedItems.some(item => item.value === option.ZzName)
        );
      }
      return this.options.filter(option => 
        option.text.toLowerCase().includes(this.searchText.toLowerCase()) &&
        !this.selectedItems.some(item => item.value === option.ZzName)
      );
    },
    isMaxSelected() {
      return this.multiple && this.selectedItems.length >= this.maxSelection;
    },
    placeholderText() {
      return this.isMaxSelected ? `已选${this.maxSelection}个(已达上限)` : this.placeholder;
    }
  },
  watch: {
    value(newVal) {
      this.selectedItems = [...newVal];
    },
    selectedItems(newVal) {
      this.$emit('input', newVal);
    }
  },
  directives: {
    'click-outside': {
      bind(el, binding, vnode) {
        el.clickOutsideEvent = function(event) {
          if (!(el === event.target || el.contains(event.target))) {
            vnode.context[binding.expression](event);
          }
        };
        document.body.addEventListener('click', el.clickOutsideEvent);
      },
      unbind(el) {
        document.body.removeEventListener('click', el.clickOutsideEvent);
      }
    }
  },
  methods: {
    toggleDropdown() {
      if (this.isMaxSelected) return;
      this.isOpen ? this.closeDropdown() : this.openDropdown();
    },
    openDropdown() {
      if (this.isMaxSelected) return;
      this.isOpen = true;
      this.$nextTick(() => {
        this.$refs.searchInput.focus();
        this.$emit('focusZzname',true)
      });
    },
    closeDropdown() {
      this.isOpen = false;
      this.searchText = '';
    },
    handleSearch() {
      if (!this.isOpen && !this.isMaxSelected) {
        this.openDropdown();
      }
    },
    toggleSelection(item) {
      if (this.isMaxSelected && !this.isSelected(item)) return;
      
      if (this.multiple) {
        const index = this.selectedItems.findIndex(i => i.value === item.value);
        if (index === -1) {
          this.selectedItems.push(item);
        } else {
          this.selectedItems.splice(index, 1);
        }
      } else {
        this.selectedItems = [item];
        this.closeDropdown();
      }
      this.searchText = '';
    },
    isSelected(item) {
      return this.selectedItems.some(i => i.value === item.value);
    },
    removeTag(index) {
      this.selectedItems.splice(index, 1);
    },
    handleBackspace(e) {
      if (e.key === 'Backspace' && this.searchText === '' && this.selectedItems.length > 0) {
        this.selectedItems.pop();
      }
    }
  
  }
}
</script>

<style scoped>
/* 之前的样式保持不变，新增以下样式 */
.max-selected-hint {
  padding: 8px 15px;
  color: #f56c6c;
  font-size: 12px;
  text-align: center;
  background-color: #fef0f0;
}

.select-control input:disabled {
  background-color: #f5f7fa;
  cursor: not-allowed;
}
.custom-select {
  position: relative;
  width: 100%;
  max-width: 400px;
  font-family: Arial, sans-serif;
}

.select-control {
  position: relative;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px 10px;
  min-height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  background-color: #fff;
}

.select-control:hover {
  border-color: #c0c4cc;
}

.selected-tags {
  flex-grow: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.tag {
  background-color: #f0f2f5;
  padding: 0 8px;
  border-radius: 3px;
  display: inline-flex;
  align-items: center;
  height: 24px;
  line-height: 24px;
  font-size: 12px;
}

.remove-tag {
  margin-left: 5px;
  cursor: pointer;
  color: #999;
}

.remove-tag:hover {
  color: #666;
}

.select-control input {
  flex-grow: 1;
  min-width: 50px;
  border: none;
  outline: none;
  height: 30px;
  padding: 0 5px;
  background: transparent;
}

.arrow-icon {
  margin-left: 5px;
  color: #c0c4cc;
  font-size: 12px;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  margin-top: 5px;
}

.dropdown-item {
  padding: 8px 15px;
  cursor: pointer;
}

.dropdown-item:hover {
  background-color: #f5f7fa;
}

.dropdown-item.selected {
  background-color: #f0f2f5;
  color: #409eff;
}

.no-results {
  padding: 8px 15px;
  color: #999;
  text-align: center;
}
</style>